package cn.gailvlun.gll.presentation.emotion.util

import cn.gailvlun.gll.chatlib.db.ChatDB2
import io.reactivex.Flowable
import io.realm.Realm
import io.realm.RealmModel
import io.realm.RealmQuery
import io.realm.RealmResults


typealias Query<T> = RealmQuery<T>.() -> Unit

fun <T : RealmModel> T.query(query: Query<T>): Flowable<RealmResults<T>>? {
    val realm = Realm.getInstance(ChatDB2.getConfiguration())
    return realm.where(javaClass)
            .withQuery(query)
            .findAllAsync()
            .asFlowable()
            .filter { it.isLoaded }
            .doOnCancel { realm.close() }
}

fun <T> T.withQuery(block: (T) -> Unit): T {
    block(this);return this
}